import { Button, Checkbox, Form, Input, Modal, Radio } from "antd"
import { PropsWithChildren, useEffect, useState } from "react";
import { TestPaperQuestionEntity } from "../../../queries/test";
import useOpen from "../../../hooks/useOpen";
import FormField from "../../../components/FormField";
import { Editor } from "primereact/editor";


export const QuestionOptions = [
  { label: "单选题", value: "SINGLE" },
  { label: "多选题", value: "MULTIPLE" },
  { label: "判断题", value: "JUDGE" },
  { label: "填空题", value: "FILL" },
  { label: "问答题", value: "ANSWER" },
]
type RenderContextProps = {
  type?: string,
  value?: string,
  onChange?: (value: string) => void,
}
const RenderContext = ({
  type = "",
  value,
  onChange,
  ...rest
}: RenderContextProps) => {
  //如果不是单选题、多选题，Context为空。
  if (!["SINGLE", "MULTIPLE"].includes(type)) {
    return null
  }
  const select: string[] = JSON.parse(value || "[]");
  return (
    <div className="flex flex-col gap-12">
      {select.map((item, key) => {
        return (
          <div
            key={key}
            className="flex gap-2"
          >
            <Editor
              className="w-full"
              value={item}
              onTextChange={(e) => {
                if (!onChange) return
                const newSelect = [...select];
                newSelect[key] = e.htmlValue || "";
                onChange(JSON.stringify(newSelect))
              }}
              {...rest}
            />
            <Button
              onClick={() => {
                if (!onChange) return
                const newSelect = [...select];
                newSelect.splice(key, 1);
                onChange(JSON.stringify(newSelect))
              }}
              danger
            >
              删除
            </Button>
          </div>
        )
      })}
      <div>
        <Button
          onClick={() => {
            if (!onChange) return
            onChange(JSON.stringify([...select, ""]))
          }}
        >
          添加选项
        </Button>
      </div>
    </div>
  )
}

const safeParse = (value: string) => {
  try {
    const result = JSON.parse(value) as string[]
    if (!Array.isArray(result)) {
      return [] as string[]
    }
    return result;
  } catch (e) {
    return [] as string[]
  }
}

type RenderAnswerProps = {
  type?: string,
  value?: string,
  onChange?: (value: string) => void,
  context?: string
}
const RenderAnswer = ({
  type = "",
  value,
  context,
  onChange,
  ...rest
}: RenderAnswerProps) => {
  const v = safeParse(context || "")
  //如果是单选题
  if (type === "SINGLE") {
    const answer = safeParse(value || "")[0]
    return <Radio.Group
      value={answer}
      onChange={(e) => {
        if (!onChange) return
        onChange(JSON.stringify([e.target.value]))
      }}
      options={v.map((_, key) => {
        const code = String.fromCharCode(key + 65)
        return {
          label: '选项' + code,
          value: code
        }
      })}
      {...rest}
    />
  }
  //如果是多选题
  if (type === "MULTIPLE") {
    const answer = safeParse(value || "")
    return <Checkbox.Group
      value={answer}
      onChange={(e) => {
        if (!onChange) return
        onChange(JSON.stringify(e.sort()))
      }}
      options={v.map((_, key) => {
        const code = String.fromCharCode(key + 65)
        return {
          label: '选项' + code,
          value: code
        }
      })}
      {...rest}
    />
  }
  //如果是填空题
  if (type === "FILL") {
    const answer = safeParse(value || "")
    return (
      <div className="flex flex-col gap-2">
        <div>
          <Button
            onClick={() => {
              if (!onChange) return
              onChange(JSON.stringify([...answer, ""]))
            }}
          >
            添加答案
          </Button>
        </div>
        {answer.map((item, key) => {
          return (
            <div
              key={key}
              className="flex gap-2 items-center"
            >
              <div className="w-20">答案{key + 1}</div>
              <Input
                value={item}
                onChange={(e) => {
                  if (!onChange) return
                  const newAnswer = [...answer];
                  newAnswer[key] = e.target.value;
                  onChange(JSON.stringify(newAnswer))
                }}
              />
              <Button
                onClick={() => {
                  if (!onChange) return
                  const newAnswer = [...answer];
                  newAnswer.splice(key, 1);
                  onChange(JSON.stringify(newAnswer))
                }}
                danger
              >
                删除
              </Button>
            </div>
          )
        })}
      </div>
    )
  }
  //如果是判断题
  if (type === "JUDGE") {
    const answer = safeParse(value || "")
    return <Radio.Group
      value={answer}
      onChange={(e) => {
        if (!onChange) return
        onChange(JSON.stringify([e.target.value.toString()]))
      }}
      options={[
        {
          label: '正确',
          value: true
        },
        {
          label: '错误',
          value: false
        }
      ]}
      {...rest}
    />
  }
  //如果是问答题
  if (type === "ANSWER") {
    return <Input.TextArea
      value={value}
      onChange={(e) => {
        if (!onChange) return
        onChange(e.target.value)
      }}
      {...rest}
    />
  }
  return null
}
type QuestionModalProps = {
  record?: TestPaperQuestionEntity,
  onFinish: (variables: any) => void,
  disabled?: boolean
}
const QuestionModal = ({
  children,
  onFinish,
  record,
  disabled = false
}: PropsWithChildren<QuestionModalProps>) => {
  const [form] = Form.useForm();
  const [open, onOpen, onCancel] = useOpen();
  const [type, setType] = useState(record?.type);
  const [context, setContext] = useState<any>(record?.content);
  useEffect(() => {
    if (record) {
      form.setFieldsValue(record)
    }
  }, [record])
  return (
    <div>
      <div
        onClick={!disabled ? onOpen : undefined}
      >
        {children}
      </div>
      <Modal
        open={open}
        onCancel={onCancel}
        width={1000}
        title={!!record ? "编辑题目" : "添加题目"}
        onOk={form.submit}
      >
        <Form
          form={form}
          onFinish={(variables) => {
            onFinish(variables)
            onCancel()
          }}
        >
          <Form.Item
            label="分值"
            name="score"
            rules={[{ required: true, message: "分值不能为空" }]}
          >
            <FormField
              type="number"
            />
          </Form.Item>
          <Form.Item
            label="排序"
            name="order"
            rules={[{ required: true, message: "排序不能为空" }]}
          >
            <FormField
              type="number"
            />
          </Form.Item>
          <Form.Item
            label="题目"
            name="name"
            rules={[{ required: true, message: "题目不能为空" }]}
          >
            <FormField
              type="editor"
            />
          </Form.Item>
          <Form.Item
            label="类型"
            name="type"
            rules={[{ required: true, message: "类型不能为空" }]}
          >
            <FormField
              type="select"
              onChange={e => {
                setType(e)
                form.setFieldValue("type", e)
              }}
              options={QuestionOptions}
            />
          </Form.Item>
          {["SINGLE", "MULTIPLE"].includes(type || "") && <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: "内容不能为空" }]}
          >
            <RenderContext
              type={type}
              onChange={e => {
                form.setFieldValue("content", e)
                setContext(e)
              }}
              value={context}
            />
          </Form.Item>}
          <Form.Item
            label="答案"
            name="answer"
            rules={[{ required: true, message: "答案不能为空" }]}
          >
            <RenderAnswer
              type={type}
              context={context}
              onChange={e => {
                form.setFieldValue("answer", e)
              }}
            />
          </Form.Item>
          <Form.Item
            label="解析"
            name="help"
          >
            <FormField
              type="editor"
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
export default QuestionModal